<template>
  <view class="order-container">
    <!-- 订单状态标签 -->
    <scroll-view class="status-tabs" scroll-x>
      <view 
        class="tab-item" 
        v-for="(item, index) in statusList" 
        :key="index"
        :class="{ active: currentStatus === item.value }"
        @click="switchStatus(item.value)"
      >
        <text>{{item.label}}</text>
      </view>
    </scroll-view>
    
    <!-- 订单列表 -->
    <view class="order-list">
      <view class="order-item" v-for="item in orderList" :key="item.orderNo">
        <view class="order-header">
          <text class="order-no">订单号：{{item.orderNo}}</text>
          <text class="order-status">{{getStatusText(item.status)}}</text>
        </view>
        <view class="order-time">{{item.createTime}}</view>
        <view class="goods-list">
          <view class="goods-item" v-for="(goods, goodsIndex) in item.items" :key="goodsIndex">
            <image class="goods-image" :src="goods.image" mode="aspectFill"></image>
            <view class="goods-info">
              <text class="goods-name">{{goods.productName}}</text>
              <text class="goods-spec">规格：{{goods.specifications}}</text>
              <view class="price-box">
                <text class="price">¥{{goods.price}}</text>
                <text class="num">x{{goods.quantity}}</text>
              </view>
            </view>
          </view>
        </view>
        <view class="order-footer">
          <view class="total">
            共{{item.items.length}}件商品 合计：
            <text class="amount">¥{{item.totalPrice}}</text>
          </view>
          <view class="btn-group">
            <button 
              class="action-btn" 
              v-for="(btn, idx) in getActionButtons(item.status)"
              :key="idx"
              @click="handleAction(btn.action, item)"
            >
              {{btn.text}}
            </button>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <view class="empty-state" v-if="orderList.length === 0">
      <text>暂无相关订单</text>
    </view>
  </view>
</template>

<script>
import { userApi } from '@/api'

export default {
  data() {
    return {
      currentStatus: 'all',
      statusList: [
        { label: '全部', value: 'all' },
        { label: '待支付', value: '0' },
        { label: '待发货', value: '1' },
        { label: '待收货', value: '2' },
        { label: '已完成', value: '3' },
        { label: '已取消', value: '4' }
      ],
      orderList: []
    }
  },
  onLoad() {
    this.loadOrders()
  },
  methods: {
    // 切换订单状态
    async switchStatus(status) {
      this.currentStatus = status
      await this.loadOrders()
    },
    
    // 加载订单列表
    async loadOrders() {
      try {
        uni.showLoading({
          title: '加载中...'
        })
        
        const status = this.currentStatus === 'all' ? '' : this.currentStatus
        const res = await userApi.getOrderList(status)
        console.log('订单列表原始数据:', res)
        
        // 处理订单数据
        this.orderList = res.map(item => ({
          orderNo: item.orderNo,
          status: item.status,
          items: item.items.map(goods => ({
            productName: goods.productName,
            specifications: goods.specifications,
            quantity: goods.quantity,
            price: Number(goods.price).toFixed(2),
            image: goods.image || '/static/images/default-product.png'
          })),
          totalPrice: Number(item.totalPrice).toFixed(2),
          createTime: item.createTime
        }))
        
        uni.hideLoading()
      } catch (error) {
        console.error('获取订单列表失败:', error)
        uni.hideLoading()
        uni.showToast({
          title: '获取订单失败',
          icon: 'none'
        })
      }
    },
    
    // 获取订单状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待支付',
        1: '待发货',
        2: '待收货',
        3: '已完成',
        4: '已取消'
      }
      return statusMap[status] || '未知状态'
    },
    
    // 获取操作按钮
    getActionButtons(status) {
      const btnMap = {
        0: [
          { text: '取消订单', action: 'cancel' },
          { text: '立即支付', action: 'pay' }
        ],
        1: [
          { text: '提醒发货', action: 'remind' }
        ],
        2: [
          { text: '确认收货', action: 'confirm' }
        ],
        3: [
          { text: '删除订单', action: 'delete' },
          { text: '再次购买', action: 'rebuy' }
        ],
        4: [
          { text: '删除订单', action: 'delete' },
          { text: '再次购买', action: 'rebuy' }
        ]
      }
      return btnMap[status] || []
    },
    
    // 处理订单操作
    async handleAction(action, order) {
      switch (action) {
        case 'pay':
          // 跳转到支付页面
          uni.navigateTo({
            url: `/pages/order/pay/index?orderNo=${order.orderNo}&amount=${order.totalPrice}`
          })
          break
          
        case 'cancel':
          uni.showModal({
            title: '提示',
            content: '确定要取消该订单吗？',
            success: async (res) => {
              if (res.confirm) {
                try {
                  // TODO: 调用取消订单接口
                  uni.showToast({
                    title: '订单已取消',
                    icon: 'success'
                  })
                  // 刷新订单列表
                  this.loadOrders()
                } catch (error) {
                  uni.showToast({
                    title: '取消订单失败',
                    icon: 'none'
                  })
                }
              }
            }
          })
          break
          
        case 'remind':
          uni.showToast({
            title: '已提醒商家发货',
            icon: 'success'
          })
          break
          
        case 'confirm':
          uni.showModal({
            title: '提示',
            content: '确认已收到商品吗？',
            success: async (res) => {
              if (res.confirm) {
                try {
                  uni.showLoading({
                    title: '处理中...'
                  })
                  await userApi.confirmReceipt(order.orderNo)
                  uni.hideLoading()
                  uni.showToast({
                    title: '确认收货成功',
                    icon: 'success'
                  })
                  // 刷新订单列表
                  this.loadOrders()
                } catch (error) {
                  uni.hideLoading()
                  uni.showToast({
                    title: error.message || '确认收货失败',
                    icon: 'none'
                  })
                }
              }
            }
          })
          break
          
        case 'delete':
          uni.showModal({
            title: '提示',
            content: '确定要删除该订单吗？',
            success: async (res) => {
              if (res.confirm) {
                try {
                  // TODO: 调用删除订单接口
                  uni.showToast({
                    title: '删除成功',
                    icon: 'success'
                  })
                  // 刷新订单列表
                  this.loadOrders()
                } catch (error) {
                  uni.showToast({
                    title: '删除失败',
                    icon: 'none'
                  })
                }
              }
            }
          })
          break
          
        case 'rebuy':
          // TODO: 实现再次购买逻辑
          uni.showToast({
            title: '再次购买功能开发中',
            icon: 'none'
          })
          break
          
        default:
          uni.showToast({
            title: `${action}功能开发中`,
            icon: 'none'
          })
      }
    }
  }
}
</script>

<style>
.order-container {
  min-height: 100vh;
  background: #f8f8f8;
}

.status-tabs {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 88rpx;
  background: #fff;
  white-space: nowrap;
  border-bottom: 1rpx solid #f5f5f5;
  z-index: 100;
}

.tab-item {
  display: inline-block;
  padding: 0 30rpx;
  height: 88rpx;
  line-height: 88rpx;
  font-size: 28rpx;
  color: #333;
}

.tab-item.active {
  color: var(--primary-color);
  position: relative;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  left: 50%;
  bottom: 0;
  transform: translateX(-50%);
  width: 40rpx;
  height: 4rpx;
  background: var(--primary-color);
  border-radius: 2rpx;
}

.order-list {
  margin-top: 108rpx;
  padding: 20rpx;
  position: relative;
  z-index: 1;
}

.order-item {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f5f5f5;
  margin-bottom: 20rpx;
}

.order-no {
  font-size: 26rpx;
  color: #666;
}

.order-status {
  font-size: 26rpx;
  color: #4caf50;
  font-weight: 500;
}

.order-time {
  font-size: 24rpx;
  color: #999;
  padding: 0 0 20rpx;
}

.goods-list {
  padding: 10rpx 0;
}

.goods-item {
  display: flex;
  padding: 20rpx 0;
  position: relative;
}

.goods-item:not(:last-child) {
  border-bottom: 1rpx solid #f8f8f8;
}

.goods-image {
  width: 160rpx;
  height: 160rpx;
  background: #f8f8f8;
  border-radius: 12rpx;
  overflow: hidden;
  z-index: 1;
  position: relative;
}

.goods-info {
  flex: 1;
  margin-left: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.goods-name {
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
  margin-bottom: 10rpx;
}

.goods-spec {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 10rpx;
}

.price-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
}

.price {
  font-size: 32rpx;
  color: #4caf50;
  font-weight: bold;
}

.num {
  font-size: 26rpx;
  color: #999;
}

.order-footer {
  border-top: 1rpx solid #f5f5f5;
  padding-top: 20rpx;
  margin-top: 10rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.total {
  font-size: 26rpx;
  color: #666;
}

.amount {
  font-size: 32rpx;
  color: #4caf50;
  font-weight: bold;
}

.btn-group {
  display: flex;
  gap: 20rpx;
  
  justify-content: flex-end;
}

.action-btn {
  margin: 0;
  height: 56rpx;
  line-height: 54rpx;
  padding: 0 30rpx;
  font-size: 26rpx;
  color: #666;
  background: #fff;
  border: 1rpx solid #ddd;
  border-radius: 28rpx;
  /* text-align: center; */
}

.action-btn:last-child {
  color: #4caf50;
  border-color: #4caf50;
}

.empty-state {
  padding: 100rpx 0;
  text-align: center;
  color: #999;
  font-size: 28rpx;
}
</style> 